const { letDataToJsFile, getBtnsStr } = require("./_utils");

const defaultOptions = {
  description: "XX列表页",
  apiPath: "@/api-mock",
  apiList: "GetUserList",
  apiDel: "DeleteUserList",
  operateBtns: ["edit", "delete"],
  extraBtns: ["add"],
  idKey: "id",
};

module.exports = {
  /**
   * 获取BaseCrud的vue文件字符串
   * @param {object[]} fields 要处理的字段
   * @param {object[]} cols 要处理的表格列
   * @param {object} options 配置信息
   * @returns
   */
  getBaseCrudStr(fields = [], cols = [], options) {
    const { description, apiPath, apiList, apiDel, operateBtns, extraBtns, idKey } = { ...defaultOptions, ...options };
    return `<!-- ${description} -->
<template>
  <BaseCrud
    :cols="cols"
    :fields="fields"
    :fetch="${apiList}"
    ${getBtnsStr(extraBtns, "extraBtns")}
    ${getBtnsStr(operateBtns, "operateBtns")}
  >
  </BaseCrud>
</template>
<script lang="ts" setup>
import { ${apiList}, ${apiDel} } from "${apiPath}";
import { FormField } from "@/core/components/form/_types";
import { TableCol } from "@/core/components/table/_types";
import { handleBtnNext } from "@/utils";
import AddEdit from "./AddEdit.vue";
import { BtnName } from "@/core/components/BaseBtn/_types";
import { CommonObj, FinallyNext } from "@/core/_types";
import { usePopup } from "@/hooks";

const { openPopup } = usePopup();
const fields: FormField[] = ${letDataToJsFile(fields)};
const cols: TableCol[] = ${letDataToJsFile(cols)};
// 处理额外按钮点击
function onExtraBtns(name: BtnName, next: FinallyNext) {
  handleBtnNext(
    {
      add: () => handleAddEdit(null, next),
    },
    name
  );
}
// 处理操作按钮点击
function onOperateBtns(name: BtnName, row: CommonObj, next: FinallyNext) {
  const { ${idKey} } = row;
  handleBtnNext(
    {
      edit: () => handleAddEdit(row, next),
      delete: () => ${apiDel}({ ${idKey} }).then(() => next()),
    },
    name
  );
}
// 新增/编辑
function handleAddEdit(row: CommonObj | null, next: FinallyNext) {
  openPopup(row ? "编辑" : "新增", [AddEdit, { data: row, refreshList: next }]);
}
</script>
<style lang="scss" scoped></style>`;
  },
};
